package com.xiaoy.github.single;

/**
 * 饿汉式(线程安全) [不推荐用]
 * <p>
 * 不支持延迟加载
 *
 * @author xiaoy
 * @since 2021-3-22 9:12
 */
class Single1 {

    private static Single1 single1 = new Single1();

    public static Single1 getInstance() {
        return single1;
    }
}

/**
 * 懒汉式(线程不安全) [不推荐用]
 * <p>
 * 优势是支持延迟加载，需要线程安全的处理
 *
 * @author xiaoy
 * @since 2021-3-22 9:16
 */
class Single2 {

    private static Single2 single2 = null;

    public static Single2 getInstance() {
        if (single2 == null) {
            single2 = new Single2();
        }
        return single2;
    }
}

/**
 * 懒汉式(线程安全) [不推荐用]
 * <p>
 * 每次获得实例都要同步，开销很大，性能很低
 *
 * @author xiaoy
 * @since 2021-3-22 9:16
 */
class Single21 {

    private static Single21 single21 = null;

    public synchronized static Single21 getInstance() {
        if (single21 == null) {
            single21 = new Single21();
        }
        return single21;
    }
}

/**
 * 懒汉式-双重校验锁(线程安全) [推荐用]
 * <p>
 * instance 成员变量加了volatile 关键字修饰，是为了防止指令重排
 *
 * @author xiaoy
 * @since 2021-3-22 9:16
 */
class Single3 {

    private volatile static Single3 single3 = null;

    public static Single3 getInstance() {
        if (single3 == null) {
            synchronized (Single3.class) {
                if (single3 == null) {
                    single3 = new Single3();
                }
            }
        }
        return single3;
    }
}

/**
 * 枚举（线程安全） [极推荐使用]
 * <p>
 * 写法简洁，代码短小精悍，防止反序列化和反射的破坏
 *
 * @author xiaoy
 * @since 2021-3-22 9:42
 */
enum Single4 {

    INSTANCE;

    public void show() {
    }
}

/**
 * 静态内部类（线程安全） [推荐用]
 * <p>
 * 优点：避免了线程不安全，延迟加载，效率高
 *
 * @author xiaoy
 * @since 2021-3-22 9:42
 */
class Single5 {

    private Single5() {

    }

    private static class SingleHolder {
        private static Single5 single5 = new Single5();
    }

    public static Single5 getInstance() {
        return SingleHolder.single5;
    }
}